import React, { PureComponent } from "react";
import { connect } from "react-redux";
import { actionCreators } from "./store";
import "./metadata.scss";
import MetadataList from "./metadataList";

import {
  Layout,
  Button,
  Form,
  Table,
  Input,
  Divider,
  Spin,
  InputNumber,
  Modal,
} from "antd";
const { Content, Header } = Layout;

class MetaData extends PureComponent {
  state = {
    addVisible: false,
    editorVisible: false,
    editData: [],
    category: true,
  };
  editRef = React.createRef();
  searchForm = React.createRef();
  formRef = React.createRef();
  SearchBtnRef = React.createRef();
  //查询
  search = () => {
    this.searchForm.current.validateFields().then((values) => {
      const userId = values.name;
      this.props.searchInfo(userId, this.props.number);
    });
    if (this.SearchBtnRef.current) {
      return;
    }
  };
  //切换页码
  onShowPageChange = (pageNum, total) => {
    if (pageNum <= 0 || pageNum > total) return;
    this.props.pageChange(pageNum);
  };
  //重置
  resetForm = () => {
    this.searchForm.current.resetFields();
    const asy = async () => {
      await this.props.getAllList();
      await this.props.backTypeFirst();
    };
    asy();
  };
  //新增类别
  handleAdd = () => {
    this.setState({
      addVisible: true,
    });
  };
  //退出新增类别
  handleCancel = () => {
    this.setState({
      addVisible: false,
    });
  };
  //保存新增类别
  addCategory = () => {
    this.formRef.current.validateFields().then((values) => {
      if (values) {
        const name = values.name;
        var description = values.description;
        if (typeof description == "undefined") {
          description = "";
        }
        const asy = async () => {
          await this.props.changeAdd(name, description, this.props.number);
          await this.handleCancel();
        };
        asy();
      }
    });
  };
  //保存编辑后的类别
  editorCategory = () => {
    console.log(this.state.editData);
    if (this.editRef.current == null) return;
    this.editRef.current.validateFields().then((values) => {
      if (values) {
        const name = values.name;
        var description = values.description;
        if (typeof description == "undefined") {
          description = "";
        }
        const asy = async () => {
          await this.props.editorCate(name, description, this.props.id);
          await this.editorCancel();
        };
        asy();
      }
    });
  };
  //取消编辑
  editorCancel = () => {
    this.setState({
      editorVisible: false,
    });
  };
  //点击编辑
  editor = (record, index) => {
    this.setState({
      editorVisible: true,
    });
    console.log(this.props.dataSource, index);
    const editorViewData = JSON.parse(
      JSON.stringify(this.props.dataSource[index])
    );
    this.setState({
      editData: editorViewData,
    });
    this.props.editor(record);
  };
  //返回类别
  back = (category) => {
    this.setState({
      category: category,
    });
    console.log(this.state.category, typeof this.state.category);
  };
  //类别首页渲染
  componentWillMount() {
    const category = sessionStorage.getItem("category");
    category === null
      ? sessionStorage.setItem("category", this.props.category)
      : sessionStorage.setItem("category", true);
    const newCategory = sessionStorage.getItem("category");
    console.log(newCategory, typeof newCategory);
    console.log(this.state.category, typeof this.state.category);
    this.setState({
      category: newCategory.toString(),
    });
    this.props.getAllList();
    console.log(this.props.dataSource);
  }
  //进入info
  view = (metaId, name) => {
    sessionStorage.setItem("category", false);
    this.setState({
      category: false,
    });
    this.props.view(metaId, name);
  };
  //删除类别
  deleteRecord = (record) => {
    this.props.deleteRecord(record);
  };
  render() {
    const {
      page,
      totalPage,
      total,
      dataSource,
      currentPage,
      changePageNum,
    } = this.props;
    const { addVisible, editData } = this.state;
    const columns = [
      {
        title: "序号",
        key: "metaId",
        dataIndex: "metaId",
        render: (text, record, index) => {
          return (currentPage - 1) * 10 + index + 1;
        },
      },
      {
        title: "类别名称",
        key: "name",
        dataIndex: "name",
        render: (text, record) => {
          return (
            <a
              onClick={() => this.view(record.metaId, record.name)}
              style={{ color: "black" }}
            >
              {text}
            </a>
          );
        },
      },
      {
        title: "元数据数量",
        key: "number",
        dataIndex: "number",
        render: (text, record) => {
          return (
            <span onClick={() => {}}>
              {this.props.metaIdsLength[record.metaId]}
            </span>
          );
        },
      },
      {
        title: "类别描述",
        key: "description",
        dataIndex: "description",
      },
      {
        title: "创建时间",
        key: "createTime",
        dataIndex: "createTime",
      },
      {
        title: "操作",
        key: "action",
        dataIndex: "action",
        render: (text, record, index) => {
          return (
            <div>
              <span
                className="action"
                onClick={() => this.view(record.metaId, record.name)}
              >
                查看
              </span>
              <Divider type="vertical" />
              <span
                className="action"
                onClick={() =>
                  this.editor(record, (this.props.currentPage - 1) * 10 + index)
                }
              >
                编辑
              </span>
              <Divider type="vertical" />
              <span
                className={
                  this.props.metaIdsLength[record.metaId] >= 1
                    ? "unaction"
                    : "action"
                }
                onClick={() => {
                  if (this.props.metaIdsLength[record.metaId] >= 1) {
                    return;
                  } else {
                    this.deleteRecord(record);
                  }
                }}
              >
                删除
              </span>
            </div>
          );
        },
      },
    ];
    const validateMessages = {
      required: "请输入",
    };
    const paginationProps = {
      onChange: (current, pageSize) => {
        changePageNum(current, pageSize);
      },
      current: currentPage,
      hideOnSinglePage: true,
      pageSize: 10,
      showSizeChanger: false,
    };
    const limitDecimals = (value) => {
      if (typeof value === "number") {
        return value;
      }
      if (typeof value !== "number") {
        if (value > this.props.total) {
          return value.replace(/^\d+/g, this.props.total);
        }
        return value.replace(/^(0+)|[^\d]+/g, "");
      }
    };
    if (this.state.category === "true") {
      return (
        <Content className="metadata-content">
          <Layout>
            <Header className="header">
              <p className="title">
                <a style={{ color: "black" }}>类别列表</a>
              </p>
              <Button
                type="primary"
                style={{ position: "absolute", right: 0 }}
                onClick={this.handleAdd}
              >
                新增类别
              </Button>
            </Header>
            <Content className="content">
              <div className="form-inline">
                <Form layout="inline" ref={this.searchForm}>
                  <Form.Item label="类别名称" colon={false} name="name">
                    <Input />
                  </Form.Item>
                  <Form.Item style={{ marginRight: 15 }}>
                    <Button
                      type="primary"
                      ref={this.SearchBtnRef}
                      onClick={this.search}
                    >
                      查询
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" onClick={this.resetForm}>
                      重置
                    </Button>
                  </Form.Item>
                </Form>
              </div>
              <div className="table-box">
                <Spin spinning={false}>
                  <Table
                    validateMessages={validateMessages}
                    columns={columns}
                    dataSource={dataSource}
                    className="table"
                    pagination={paginationProps}
                    rowKey="metaId"
                  />
                  <div className="footer">
                    显示
                    <InputNumber
                      min={1}
                      formatter={limitDecimals}
                      parser={limitDecimals}
                      max={totalPage}
                      defaultValue={page}
                      value={currentPage}
                      onChange={(e) => {
                        this.onShowPageChange(e, total);
                      }}
                    />
                    项结果，共{totalPage}项
                  </div>
                </Spin>
              </div>
            </Content>
          </Layout>
          <Modal
            destroyOnClose
            title={<div className="title-Style">新建元数据类别</div>}
            visible={addVisible}
            onCancel={this.handleCancel}
            bodyStyle={{ backgroundColor: "#f0f3f6" }}
            footer={
              <div className="footer-Style">
                <Button
                  type="primary"
                  style={{ color: "white", borderRadius: 5 }}
                  onClick={this.addCategory}
                >
                  保存
                </Button>
                <Button
                  style={{ color: "#007cdb", borderRadius: 5 }}
                  onClick={this.handleCancel}
                >
                  取消
                </Button>
              </div>
            }
          >
            <Form
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 20 }}
              validateMessages={validateMessages}
              ref={this.formRef}
            >
              <Form.Item
                label={<span className="formItem-Style">类别名称</span>}
                name="name"
                rules={[{ required: true, message: "请输入类别名称" }]}
              >
                <Input placeholder="请输入类别名称" />
              </Form.Item>
              <Form.Item
                label={<span className="formItem-Style">类别描述</span>}
                name="description"
              >
                <Input.TextArea />
              </Form.Item>
            </Form>
          </Modal>
          <Modal
            destroyOnClose
            title={<div className="title-Style">编辑元数据类别</div>}
            visible={this.state.editorVisible}
            onCancel={this.editorCancel}
            bodyStyle={{ backgroundColor: "#f0f3f6" }}
            footer={
              <div className="footer-Style">
                <Button
                  type="primary"
                  style={{ color: "white", borderRadius: 5 }}
                  onClick={this.editorCategory}
                >
                  保存
                </Button>
                <Button
                  style={{ color: "#007cdb", borderRadius: 5 }}
                  onClick={this.editorCancel}
                >
                  取消
                </Button>
              </div>
            }
          >
            <Form
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 20 }}
              validateMessages={validateMessages}
              ref={this.editRef}
            >
              <Form.Item
                label={<span className="formItem-Style">类别名称</span>}
                rules={[{ required: true, message: "请输入类别名称" }]}
                initialValue={editData.name}
                name="name"
              >
                <Input placeholder="请输入类别名称" />
              </Form.Item>
              <Form.Item
                label={<span className="formItem-Style">类别描述</span>}
                name="description"
                initialValue={editData.description}
              >
                <Input.TextArea />
              </Form.Item>
            </Form>
          </Modal>
        </Content>
      );
    } else {
      return <MetadataList back={this.back} />;
    }
  }
}

const mapStateToProps = (state) => {
  return {
    page: state.getIn(["MetaData", "page"]),
    totalPage: state.getIn(["MetaData", "totalPage"]),
    total: state.getIn(["MetaData", "total"]),
    name: state.getIn(["MetaData", "name"]),
    dataSource: state.getIn(["MetaData", "dataSource"]),
    pageNum: state.getIn(["MetaData", "pageNum"]),
    pageSize: state.getIn(["MetaData", "pageSize"]),
    currentPage: state.getIn(["MetaData", "currentPage"]),
    number: state.getIn(["MetaData", "number"]),
    categoryName: state.getIn(["MetaData", "categoryName"]),
    id: state.getIn(["MetaData", "id"]),
    metaIdsLength: state.getIn(["MetaData", "metaIdsLength"]),
  };
};

const mapDispatchToProps = (dispatch) => ({
  getAllList() {
    dispatch(actionCreators.getAllList());
  },
  editor(record) {
    const id = record.metaId;
    dispatch(actionCreators.editor(id));
  },
  deleteRecord(record) {
    dispatch(actionCreators.deleteRecord(record.metaId));
  },
  searchInfo(userId, number) {
    dispatch(actionCreators.searchInfo(userId, number));
  },
  changeAdd(name, description, number) {
    dispatch(actionCreators.newAdd(name, description, number));
  },
  changePageNum(current, pageSize) {
    dispatch(actionCreators.changePageNum(current, pageSize));
  },
  pageChange(pageNum) {
    dispatch(actionCreators.changePageSize(pageNum));
  },
  editorCate(name, description, id) {
    dispatch(actionCreators.editCategory(name, description, id));
  },
  view(recordId, recordName) {
    dispatch(actionCreators.view(recordId, recordName));
  },
  backTypeFirst() {
    dispatch({ type: "back_type_first" });
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(MetaData);
